import { defineStore } from 'pinia'
import { createPersistedState } from 'pinia-plugin-persistedstate'
import { userApi } from '@/api/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    user: null,
    isLoggedIn: false,
    userId: null,
    username: '',
    email: null,
    avatar: null,
    roles: [],
    permissions: [],
    isAdmin: false // 新增管理员状态
  }),
  
  actions: {
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
      this.isLoggedIn = true
    },
    
    setUser(user) {
      this.user = user
      this.isLoggedIn = true
      this.userId = user.userId || user.user_id || user.id
      this.username = user.username
      this.email = user.email
      this.avatar = user.avatar
      this.roles = user.roles || []
      this.permissions = user.permissions || []
      // 判断是否是管理员 (可以根据角色或特定用户ID判断)
      this.isAdmin = this.hasRole('admin') || this.userId === 1
      
      console.log('设置用户信息:', { 
        userId: this.userId, 
        isLoggedIn: this.isLoggedIn,
        username: this.username,
        isAdmin: this.isAdmin 
      })
    },
    
    async checkAuth() {
      const token = localStorage.getItem('token')
      if (token) {
        try {
          const response = await userApi.getUserInfo()
          console.log('用户信息响应:', response)
          
          if (response.status === 'Success' || response.user_id) {
            this.setUser({
              user_id: response.user_id || response.id,
              username: response.username || '',
              email: response.email || '',
              avatar: response.avatar || null,
              roles: response.roles || [],
              permissions: response.permissions || [],
              token: token
            })
            return true
          } else {
            this.logout()
            return false
          }
        } catch (error) {
          console.error('验证用户信息失败:', error)
          this.logout()
          return false
        }
      }
      return false
    },
    
    logout() {
      this.isLoggedIn = false
      this.username = ''
      this.token = null
      this.userId = null
      this.isAdmin = false
      localStorage.removeItem('token')
      // 清除持久化数据
      localStorage.removeItem('user-store')
    },
    
    isAuthor(authorId) {
      return this.isLoggedIn && this.userId === authorId
    },
    
    hasPermission(permission) {
      return this.permissions.includes(permission)
    },
    
    hasRole(role) {
      return this.roles.includes(role)
    },
    
    updateProfile(profileData) {
      if (profileData.username) this.username = profileData.username
      if (profileData.email) this.email = profileData.email
      if (profileData.avatar) this.avatar = profileData.avatar
    },
    
    // 新增管理员专用方法
    async adminLogin(credentials) {
      try {
        const response = await userApi.adminLogin(credentials)
        if (response.user_id && (response.roles?.includes('admin') || response.user_id === 1)) {
          this.setUser({
            ...response,
            token: response.token
          })
          return { success: true }
        } else {
          return { success: false, message: '无管理员权限' }
        }
      } catch (error) {
        console.error('管理员登录失败:', error)
        return { success: false, message: error.response?.data?.message || '登录失败' }
      }
    },
    
    // 获取所有用户 (管理员权限)
    async fetchAllUsers() {
      if (!this.isAdmin) throw new Error('无权限访问')
      return await userApi.getAllUsers()
    },
    
    // 获取所有文章 (管理员权限)
    async fetchAllArticles() {
      if (!this.isAdmin) throw new Error('无权限访问')
      return await userApi.getAllArticles()
    }
  },
  
  getters: {
    getToken: (state) => state.token,
    isAuthenticated: (state) => !!state.token,
    // 新增管理员状态getter
    isAdministrator: (state) => state.isAdmin,
    // 获取用户基本信息
    userInfo: (state) => ({
      id: state.userId,
      name: state.username,
      email: state.email,
      avatar: state.avatar,
      isAdmin: state.isAdmin
    })
  },
  
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['isLoggedIn', 'userId', 'username', 'email', 'avatar', 'roles', 'permissions', 'isAdmin']
  }
})